<template>
  <div class="register">
    <div v-if="this.status == 'registerbox'" id="registerbox" class="registerbox">
      <h1 style="margin-top: 0px">注册账号</h1>
      <p>请选择您在日常教学中的实际身份</p>
      <div @click="changeStatus('registerboxteacher')"><img style="float: left" src="https://www.ketangpai.com/Public/Home/img/teacher.png">
        <el-button
          style="width: 330px;float: left;height: 64px;margin-left: 40px;background-color: #32BAF0;color: white;font-weight: 500;font-size: 18px">
          我是老师/助教
        </el-button>
      </div>
      <div @click="changeStatus('registerboxstudent')"><img style="float: left" src="https://www.ketangpai.com/Public/Home/img/student.png">
        <el-button
          style="width: 330px;float: left;height: 64px;margin-left: 40px;background-color: #32BAF0;color: white;font-weight: 500;font-size: 18px">
          我是学生
        </el-button>
      </div>
      <a href="#/login">已有账号？<label style="color: #569fe0;cursor: pointer">去登陆</label></a>
    </div>


    <div v-if="this.status == 'registerboxstudent'" class="registerbox2" id="registerboxstudent">
      <el-form :rules="rules" :model="studentForm" ref="studentFrom">
        <el-form-item>
          <a @click="changeStatus('registerbox')" class="el-icon-back"
             style="font-size: 50px;color: #818181;font-weight: 600;float: left;cursor: pointer"></a><label
          style="font-size: 32px;float: left;margin-left: 20px">学生注册</label>
        </el-form-item>
        <el-form-item prop="studentAccount">
          <el-input v-model="studentForm.studentAccount" auto-complete="off" placeholder="邮箱/手机"></el-input>
        </el-form-item>
        <el-form-item prop="studentPassword">
          <el-input v-model="studentForm.studentPassword" auto-complete="off" placeholder="密码" show-password></el-input>
        </el-form-item>
        <el-form-item prop="studentPassword2">
          <el-input v-model="studentForm.StudentPassword2" auto-complete="off" placeholder="再次输入密码" show-password></el-input>
        </el-form-item>
        <el-form-item prop="studentName">
          <el-input v-model="studentForm.studentName" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item prop="studentId">
          <el-input v-model="studentForm.studentId" placeholder="学号"></el-input>
        </el-form-item>
        <el-form-item prop="school">
          <el-input v-model="studentForm.school" placeholder="学校"></el-input>
        </el-form-item>
<!--        <el-form-item prop="studentCode">-->
<!--          <el-input @blur="check()" v-model="studentForm.studentCode" placeholder="验证码" style="width: 60%"></el-input>-->
<!--&lt;!&ndash;          <img width="140px" height="48px" style="float: right;border: #818181 solid 1px;cursor: pointer"&ndash;&gt;-->
<!--&lt;!&ndash;               @click="random" v-model="r" :src="verification+r">&ndash;&gt;-->
<!--          <div class="code" @click="refreshCode">-->
<!--            <img :src="codeSrc">-->
<!--          </div>-->
<!--        </el-form-item>-->
        <el-form-item>
          <el-button @click="submitForm('studentFrom')"
                     style="width: 100%;height: 50px;background-color: #32BAF0;color: white">注册为学生
          </el-button>
        </el-form-item>
        <el-form-item>
          <a style="float: right;cursor: pointer" href="#/login">已有账号？<label
            style="color: #32BAF0;cursor: pointer">去登陆</label></a>
        </el-form-item>
      </el-form>
<!--      <StudentRegister></StudentRegister>-->
    </div>


    <div v-if="this.status == 'registerboxteacher'" class="registerbox2" id="registerboxteacher" >
<!--<TeacherRegister></TeacherRegister>-->
      <el-form :model="teacherForm" ref="teacherFrom" :rules="rules">
        <el-form-item>
          <a @click="changeStatus('registerbox')" class="el-icon-back"
             style="font-size: 50px;color: #818181;font-weight: 600;float: left;cursor: pointer"></a><label
          style="font-size: 32px;float: left;margin-left: 20px">老师/助教注册</label>
        </el-form-item>
        <el-form-item prop="teacherAccount">
          <el-input v-model="teacherForm.teacherAccount" auto-complete="off" placeholder="邮箱/手机"></el-input>
        </el-form-item>
        <el-form-item prop="teacherPassword">
          <el-input v-model="teacherForm.teacherPassword" auto-complete="off" placeholder="密码" show-password></el-input>
        </el-form-item>
        <el-form-item prop="teacherPassword2">
          <el-input v-model="teacherForm.teacherPassword2" auto-complete="off" placeholder="再次输入密码" show-password></el-input>
        </el-form-item>
        <el-form-item prop="teacherName">
          <el-input v-model="teacherForm.teacherName" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item prop="teacherId">
          <el-input v-model="teacherForm.teacherId" placeholder="教师号"></el-input>
        </el-form-item>
        <el-form-item prop="college">
          <el-input v-model="teacherForm.college" placeholder="学校"></el-input>
        </el-form-item>
<!--        <el-form-item prop="teacherCode">-->
<!--&lt;!&ndash;          <el-input @blur="check()" v-model="teacherForm.teacherCode" placeholder="验证码" style="width: 60%"></el-input>&ndash;&gt;-->
<!--          <div class="code" @click="refreshCode">-->
<!--            <img :src="codeSrc">-->
<!--          </div>-->
<!--        </el-form-item>-->
        <el-form-item>
          <el-button @click="submitForm('teacherFrom')"
                     style="width: 100%;height: 50px;background-color: #32BAF0;color: white">注册为老师/助教
          </el-button>
        </el-form-item>
        <el-form-item>
          <a style="float: right;cursor: pointer" href="#/login">已有账号？<label
            style="color: #32BAF0;cursor: pointer">去登陆</label></a>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
  import axios from "axios";
  import md5 from 'js-md5'
  import SIdentify from "../../components/identify";
  import sIdentify from "../../components/identfiy_2";
  import http from "../../utils/http.js";
  export default {
    name: "Register",
    components:{
      SIdentify:SIdentify,
      sIdentify:sIdentify
    },

    data() {

      let phoneNumber = /^(13[0-9]|17[0-9]|14[5|7] |15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/;
      let emailNumber = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
      let password = /^[a-zA-Z]\w{5,17}$/;
      let id=/^[A-Za-z0-9]{8}$/
      var validStudentAccount= (rule, value, callback) => {
        var i=0;
        var flag=false;
        for (i=0;i<this.accountAll.length;i++){
          if(this.studentForm.studentAccount==this.accountAll[i].account){
            flag=true;
            break;
          }
        }
        if(flag ){
          callback(new Error("账号已存在"));
        }else if (phoneNumber.test(value)) {
          callback();
        } else if (emailNumber.test(value)) {
          callback();
        }
        else {
          callback(new Error("输入的邮箱/账号/手机号不合法"));
        }
      };
      var validTeacherAccount = (rule, value, callback) => {
        var i=0;
        var flag=false;
        for (i=0;i<this.accountAll.length;i++){
          if(this.teacherForm.teacherAccount==this.accountAll[i].account){
            flag=true;
            break;
          }
        }
        if(flag ){
          callback(new Error("账号已存在"));
        }else if (phoneNumber.test(value)) {
          callback();
        } else if (emailNumber.test(value)) {
          callback();
        }
        else {
          callback(new Error("输入的邮箱/账号/手机号不合法"));
        }
      };
      var validPassword = (rule, value, callback) => {
        if (password.test(value)) {
          callback();
        } else {
          callback(new Error("以字母开头，长度在6~18之间，只能包含字母、数字和下划线"))
        }
      }

      var phoneValid = (rule, value, callback) => {
        if (phoneNumber.test(value)) {
          callback();
        } else {
          callback(new Error("输入的手机号不正确"))
        }
      }
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else if (!password.test(value)) {
          callback(new Error('密码格式以字母开头，长度在6~18之间，只能包含字母、数字和下划线'))
        } else {
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.teacherForm.teacherPassword) {
          callback(new Error('两次输入密码不一致!'));
        } else if (!password.test(value)) {
          callback(new Error('密码格式以字母开头，长度在6~18之间，只能包含字母、数字和下划线'))
        } else {
          callback();
        }
      };
      var validatePass3 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else if (!password.test(value)) {
          callback(new Error('密码格式以字母开头，长度在6~18之间，只能包含字母、数字和下划线'))
        } else {
          callback();
        }
      };
      var validatePass4 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.studentForm.studentPassword) {
          callback(new Error('两次输入密码不一致!'));
        } else if (!password.test(value)) {
          callback(new Error('密码格式以字母开头，长度在6~18之间，只能包含字母、数字和下划线'))
        } else {
          callback();
        }
      };
      var validStudentId = (rule,value,callback) =>{
        var i=0;
        var flag=false;
        for (i=0;i<this.student.length;i++){
          if(this.studentForm.studentId==this.student[i].studentId){
            flag=true;
            break;
          }
        }
        if(flag){
          callback(new Error("学号已经存在"));
        }else if(!id.test(value)){
          callback("输入正确的八位数字和字母组成的Id");
        }else{
          callback();
        }
      };
      var validTeacherId = (rule,value,callback) =>{
        var i=0;
        var flag=false;
        for (i=0;i<this.teacher.length;i++){
          if(this.teacherForm.teacherId==this.teacher[i].teacherId){
            flag=true;
            break;
          }
        }
        if(flag){
          callback(new Error("教师号已经存在"));
        }else if(!id.test(value)){
          callback("输入正确的八位数字和字母组成的Id");
        }else{
          callback();
        }
      }
      return {
        flag:true,
        status:'registerbox',
        identifyTeacherCodes: "1234567890",
        identifyStudentCodes: "1234567890",
        identifyStudentCode: "",
        identifyTeacherCode:"",
        codeFlag:'',

        codeSrc:"http://localhost:8080/requestCode/"+new Date(),
        s:"",
        accountAll:[

        ],
        student:[

        ],
        teacher:[

        ],
        teacherForm: {
          teacherAccount: '',
          teacherPassword: '',
          teacherPassword2: '',
          teacherName: '',
          teacherId: '',
          college: '',
          teacherCode: '',
        },
        studentForm: {
          studentAccount: '',
          studentPassword: '',
          studentPassword2: '',
          studentName: '',
          studentId: '',
          school: '',
          studentCode: '',
        },
        rules: {
          studentAccount: [
            {required: true, message: '请输入邮箱/手机号', trigger: 'blur'},
            {validator: validStudentAccount, trigger: 'blur'},
          ],
          teacherAccount: [
            {required: true, message: '请输入邮箱/手机号', trigger: 'blur'},
            {validator: validTeacherAccount, trigger: 'blur'},
          ],
          teacherPassword: [
            {validator: validatePass, trigger: 'blur'}
          ],
          teacherPassword2: [
            {validator: validatePass2, trigger: 'blur'}
          ],
          teacherName: [
            {required: true, message: '请输入名字', trigger: 'blur'},
            {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'},
            {
              required: true,
              pattern: /^[\u4e00-\u9fa5_a-zA-Z0-9.·-]+$/,
              message: '姓名不支持特殊字符',
              trigger: 'blur'
            }
          ],
          studentName: [
            {required: true, message: '请输入名字', trigger: 'blur'},
            {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'},
            {
              required: true,
              pattern: /^[\u4e00-\u9fa5_a-zA-Z0-9.·-]+$/,
              message: '姓名不支持特殊字符',
              trigger: 'blur'
            }
          ],
          teacherId: [
            {required: true, message: '学号不能为空'},
            {validator: validTeacherId, trigger: 'blur'}
          ],
          studentId: [
            {required: true, message: '教师号不能为空'},
            {validator: validStudentId, trigger: 'blur'}
          ],
          college: [
            {required: true, message: '请输入学校', trigger: 'blur'},
            {
              required: true,
              pattern: /^[\u4e00-\u9fa5_a-zA-Z0-9.·-]+$/,
              message: '学校不支持特殊字符',
              trigger: 'blur'
            }
          ],
          school: [
            {required: true, message: '请输入名字', trigger: 'blur'},
            {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'},
            {
              required: true,
              pattern: /^[\u4e00-\u9fa5_a-zA-Z0-9.·-]+$/,
              message: '姓名不支持特殊字符',
              trigger: 'blur'
            }
          ],
          teacherCode: [
            {required: true, message: '验证码不能为空'},
            // {type: 'number', message: '输入正确的验证码'},
          ],
          studentCode: [
            {required: true, message: '验证码不能为空'},
            // {type: 'number', message: '输入正确的验证码'},
          ],
          StudentPassword: [
            {validator: validatePass3, trigger: 'blur'}
          ],
          StudentPassword2: [
            {validator: validatePass4, trigger: 'blur'}
          ],
        }
      };
    },
    created() {
      //this指的是当前的vue对象，把vue对象赋给_this
      const _this = this
      // this.axios.get('findAllAccount').then(function (resp) {
      //   //回调函数中的this指的是回调
      //   //把data数据赋给_this，即vue对象
      //   _this.accountAll = resp.data
      // })
      // this.axios.get('findAllStudents').then(function (resp) {
      //   //回调函数中的this指的是回调
      //   //把data数据赋给_this，即vue对象
      //   _this.student = resp.data
      // })
      // this.axios.get('getAllTeachers').then(function (resp) {
      //   //回调函数中的this指的是回调
      //   //把data数据赋给_this，即vue对象
      //   _this.teacher = resp.data
      // })
    },

    methods: {
      changeStatus(status){
        this.status = status
      },
      refreshCode() {
        this.codeSrc="http://localhost:8080/requestCode/"+new Date();
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if(formName=='studentFrom') {
              this.codeFlag = '';
              let s=this.studentForm
              let student={
                name:s.studentName,
                studentId:s.studentId,
                school:s.school,
                password:md5(s.studentPassword),
                phoneNum:s.studentAccount,
              }
              http.post('student/register',student).then((response) => {
                if(response.data.code==200) {
                  this.$message({
                    message: '注册成功',
                    type: 'success'
                  });
                  this.$router.push("/login")
                }else{
                  this.$message.error(response.data.message);
                }
                })
                .catch(function (error) {
                  this.$message.error({
                    message: '注册失败,出现错误',
                    type: 'error'
                  });
                  // this.$router.push("/login")
                });
            }else{
              let t=this.teacherForm
              let teacher={
                name:t.teacherName,
                teacherId:t.teacherId,
                college:t.college,
                password:t.teacherPassword,
                phoneNum:t.teacherAccount,
              }
              teacher.password = md5(this.teacherForm.teacherPassword)
              http.post('teacher/register',teacher
                )
                .then((response) => {
                  if(response.data.code==200) {
                    this.$message({
                      message: response.data.message,
                      type: 'success'
                    });
                    this.$router.push("/login")
                  }else{
                    this.$message.error(response.data.message);
                  }
                })
                .catch(function (error) {
                  this.$message({
                    message: '注册失败,出现错误',
                    type: 'error'
                  });
                  this.$router.push("/login")
                });
            }
          } else {
            this.$message({
              message: '注册失败，表单不合法',
              type: 'error'
            });
            return false;
          }
        });

      },
    }
  }
</script>

<style scoped>
  .register {
    width: 1520px;
    height: 750px;
    background-image: url("https://www.ketangpai.com/Public/Home/img/reg-bg-01.jpg");
    position: relative;
  }

  .registerbox {
    width: 480px;
    height: 504px;
    background-color: white;
    position: absolute;
    top: 80px;
    left: 500px;
    text-align: left;
    padding: 30px;
  }

  .registerbox div {
    margin-top: 40px;
    width: 480px;
    height: 70px;
  }

  .registerbox a {
    text-decoration: none;
    color: #818181;
    float: right;
    margin-top: 30px;
    margin-right: 40px;
  }

  .registerbox2 {
    width: 440px;
    height: 554px;
    background-color: white;
    position: absolute;
    top: 80px;
    left: 500px;
    text-align: left;
    padding: 30px;
  }

  .el-form-item {
    margin-bottom: 16px;
  }


  .el-form-item__error {
    right: 0px !important;
  }
</style>
<style>

  .el-input__inner {
    width: 100%;
    height: 40px !important;
    font-size: 20px;
  }

  a {
    text-decoration: none;
    color: #818181;
  }
  .code {
    width: 112px;
    height: 35px;
    border: 1px solid #ccc;
    float: right;
    border-radius: 2px;
    margin-right: 20px;
  }
</style>
